/*
 * Powered By 
 * Since 2010 - 2016
 */

package com.rf.sys.control;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rf.sys.annotation.SystemLog;
import com.rf.sys.bean.UserBean;
import com.rf.sys.frm.BaseController;
import com.rf.sys.model.DepUser;
import com.rf.sys.model.User;
import com.rf.sys.model.UserLoginLog;
import com.rf.sys.service.DepUserService;
import com.rf.sys.service.DepartmentService;
import com.rf.sys.service.UserService;
import com.rf.sys.utils.ConfigUtils;
import com.rf.sys.utils.JsonUtils;
import com.rf.sys.utils.PageUtils;
import com.rf.sys.utils.PasswordHelper;
import com.rf.sys.utils.UuidUtil;

@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController{
	/**
	 * 日志
	 */
	private static Logger log = LoggerFactory.getLogger(UserController.class);
	private static final long serialVersionUID = -120160623160132442L;
	
	@Resource
	private UserService userService;
	
	@Resource
	private DepUserService depUserService;
	
	@Resource
	private DepartmentService departmentService;
	/**
	 * 初始化页面信息
	 * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
	 */
	@RequestMapping(value = "index")
    public ModelAndView index (HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("sys/user/user_list");
		return modelAndView; 
    }
    
    /**
	 * 搜索页面信息
	 * @param Page,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "query")
    @ResponseBody
    public void query (PageUtils pageUtils, User user, HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	Map searchMap = userService.getUserPage(user, pageUtils);
    	super.responsePrint(request, response, JsonUtils.mapToJson(searchMap));
    }
    
    /**
     * 编辑页面初始化信息
     * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	ModelAndView modelAndView = new ModelAndView();
		String id = request.getParameter("id");
		User user = new User();
		UserBean userbean = new UserBean();
		Session session = SecurityUtils.getSubject().getSession();
		if(id != null && !id.equals("")){
			user = userService.getUserByID(id);	
			userbean.setId(user.getId());
			userbean.setAccountName(user.getAccountName());
			userbean.setCreateTime(user.getCreateTime());
			userbean.setCredentialsSalt(user.getCredentialsSalt());
			userbean.setDescription(user.getDescription());
			userbean.setPassword(user.getPassword());
			userbean.setState(user.getState());
			userbean.setUserName(user.getUserName());
			if(user.getId() != null && !user.getId().equals("")){
				DepUser depUser = depUserService.getDepUserByUserID(user.getId());
				if(depUser !=null){
					userbean.setDepartment(depUser.getDepId());
				}
			}
		}else{
			String department= (String)session.getAttribute("depSessionId");
			if(department != null && !department.equals("")){
				userbean.setDepartment(department);
			}
			userbean.setState(ConfigUtils.USERENABLESTATE);//启用状态
		}
		modelAndView.addObject("user", userbean);
		modelAndView.setViewName("sys/user/user_edit");
        return modelAndView; 
    }
    
    /**
     * 保存数据信息
     * @param User,request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "save")
    @SystemLog(module="系统管理",methods="用户管理-新增用户")//凡需要处理业务逻辑的.都需要记录操作日志
    public void save (UserBean userBean, HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	String ret = "success";
    	Session session = SecurityUtils.getSubject().getSession();
    	User user = new User();
    	user.setUserName(userBean.getUserName());
    	user.setAccountName(userBean.getAccountName());
    	user.setDescription(userBean.getDescription());
    	user.setState(userBean.getState());
    	if(userBean != null){
    		if(userBean.getId()!=null && !userBean.getId().equals("")){
    			//修改
    			user.setId(userBean.getId());
    			userService.updateUser(user);
    		}else{
    			List<User> userList = userService.getUserRepeat(user);
	    		if(userList != null && userList.size()>0){
					ret = "repeat";//登陆名已存在
				}else{
	    			//新增
	    			user.setCredentialsSalt(UuidUtil.get32UUID());
	    			user.setPassword(ConfigUtils.PASSWORD);
	    			user = PasswordHelper.encryptPassword(user);
	    			user.setCreateTime(new Date());
	    			user.setCreateUser((String)session.getAttribute("userSessionId"));
	    			userService.addUser(user);
	    			DepUser depUser = new DepUser();
	    			depUser.setDepId(userBean.getDepartment());
	    			depUser.setUserId(user.getId());
	    			depUser.setId(UuidUtil.get32UUID());
	    			depUserService.addDepUser(depUser);
		    		}
			}
    		
    	}
		super.resPrint(request, response, ret);//成功
    }
    
    /**
     * 删除数据信息
     * @param request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "delete")
    @ResponseBody
    public void delete (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String ids = request.getParameter("ids");
    	userService.deleteUser(ids);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 更新数据状态
     * @param User,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "updateState")
    @ResponseBody
    public void updateState (User user, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	userService.updateUser(user);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 给用户分配角色
     * @param request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "allot")
    @ResponseBody
    public void allot (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String userid = request.getParameter("userid");
    	String roleid = request.getParameter("roleid");
    	userService.allot(userid, roleid);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
}